package lhc.learn.bio;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.math.NumberUtils;

import java.net.ServerSocket;
import java.net.Socket;

/**
 * java bio 学习
 * Created by Lihc on 2016/3/24.
 */
public class TimeServer {
    private static boolean usePool = true;

    public static void main(String[] args) {
        int port = 8080;
        if (ArrayUtils.isNotEmpty(args)) {
            port = NumberUtils.toInt(args[0], port);
        }
        ServerSocket serverSocket = null;
        TimeServerHandlerExecutePool pool = null;
        if (usePool) {
            pool = new TimeServerHandlerExecutePool(50, 1000);
        }
        try {
            serverSocket = new ServerSocket(port);
            Socket socket = null;
            while (true) {
                socket = serverSocket.accept();
                System.out.println("have a new socket");
                if (usePool && null != pool) {
                    pool.execute(new TimeServerHandler(socket));
                } else {
                    new Thread(new TimeServerHandler(socket)).start();
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(serverSocket);
        }

    }

}
